package com.ttc.ssm.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * Created by 58296 on 2016/8/9.
 */
public class FileUtils {

    public static void deleteFile(String name, HttpServletRequest request) {
        if (!TextUtils.isEmpty(name)){
            String pic_path=request.getSession().getServletContext().getRealPath("upload/customer/");
            String old_file_name = pic_path + name;
            File old_File = new File(old_file_name);
            if(old_File.exists()){
                old_File.delete();
            }
        }
    }

    public static String createFile(MultipartFile temp_file, HttpServletRequest request) throws Exception{
        String originalFilename = temp_file.getOriginalFilename();
        if(temp_file !=null && originalFilename !=null && originalFilename.length()>0) {
            //存储图片的物理路径
            String file_path=request.getSession().getServletContext().getRealPath("upload/customer/");
            //新的图片名称
            String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println(file_path + newFileName);
            //新图片
            File newFile = new File(file_path + newFileName);

            //将内存的数据写入磁盘
            temp_file.transferTo(newFile);

            return newFileName;
        }
        return null;
    }
}
